const lodash = require('lodash')
const Base = require('../entities/Base')
import { DeepCopy } from '@/utils/Utils'
import { dictToWhere } from '@/utils/sqlUtils'

const TaskDao = {
    table: 'task_group',
    pageSize: Base.pageSize
}

TaskDao.initialForm = (usageScope) => {
    return JSON.parse(JSON.stringify({
        id: 0,
        name: "",
        ruleId: "",
        moduleId: "",
        accountId: "",
        homeUrl: "",
        targetUrl: "",
        dataFields: [],
        platformId: "",
        sourceType: "",
        promotionIds: [],
        usageScope: usageScope,
    }))
}

TaskDao.toObject = (row) => {
    let obj = DeepCopy(row)
    if (lodash.isString(row.dataFields)) {
        obj.dataFields = JSON.parse(row.dataFields)
    }
    if (lodash.isString(row.promotionIds)) {
        obj.promotionIds = JSON.parse(row.promotionIds)
    }
    return obj
}

TaskDao.fetchPage = async (page, usageScope) => {
    let whereSql = "where usageScope = " + usageScope
    return await Base.fetchPage(TaskDao.table, whereSql, page)
}

TaskDao.fetchAll = async (whereDict) => {
    let whereSql = dictToWhere(whereDict)
    return await Base.fetchWhere(TaskDao.table, whereSql)
}

TaskDao.fetchCount = async (page, usageScope) => {
    let count = await TaskDao.countWhere(usageScope)
    let datas = await TaskDao.fetchPage(page, usageScope)
    return { count, datas }
}

TaskDao.countWhere = async (usageScope) => {
    let whereSql = "where usageScope = " + usageScope
    return await Base.countWhere(TaskDao.table, whereSql)
}

TaskDao.save = async (obj) => {
    if (!lodash.isString(obj.dataFields)) {
        obj.dataFields = JSON.stringify(obj.dataFields)
    }
    if (!lodash.isString(obj.promotionIds)) {
        obj.promotionIds = JSON.stringify(obj.promotionIds)
    }
    return await Base.save(TaskDao.table, obj)
}

TaskDao.delete = async (id) => {
    return await Base.delete(TaskDao.table, id)
}

export { TaskDao }


